package com.pactera.mavenweb.controller;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
//import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
//@RequestMapping("/error")
public class LoginLogoutController {
	
	protected static Logger logger = Logger.getLogger(LoginLogoutController.class);
	
	/** 
	 * 指向登录页面 
	 */
	// used in commonpage_useless.jsp, useless?
	@RequestMapping(value = "/auth/login", method = RequestMethod.GET)
	public String getLoginPage(
			@RequestParam(value = "error", required = false) boolean error,
			ModelMap model) {
		
		logger.debug("Received request to show login page");
		
		if (error == true) {
			// Assign an error message
			model.put("error",
					"You have entered an invalid username or password!");
		} else {
			model.put("error", "");
		}
//		return "loginpage";
		return "login";
	}
	
	/** 
	 * 指定无访问额权限页面 
	 *
	 * @return 
	 */
	@RequestMapping(value = "/error/denied", method = RequestMethod.GET)
//	public String getDeniedPage() {
//		
//		logger.debug("Received request to show denied page");
//		
//		return "denied";
//	}
//	@RequestMapping(method=RequestMethod.GET, value="/accessDenied.do")
	public String accessDenied(ModelMap model, HttpServletRequest request) {
		AccessDeniedException ex = new AccessDeniedException("access denied"); 
//				(AccessDeniedException) request.getAttribute(AccessDeniedHandlerImpl.SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY);
		StringWriter sw = new StringWriter();
		model.addAttribute("errorDetails", ex.getMessage());
		ex.printStackTrace(new PrintWriter(sw));
		model.addAttribute("errorTrace", sw.toString());
		return "/denied";
	}
	
	
} 